<template>
	<gui-page ref="guiPage" :customHeader="true">
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :title="$t('finishedInventory.inventoryParticulars')" :rightText="$t('finishedInventory.detailsView')" @clickRight="clickRight"></nav-bar-custom>
		</template>
		<template v-slot:gBody>
			<view class="distributed">
				<!-- 库存信息-->
				<view class="custom-form-card" >
					<view class="custom-card-itemOne addflex">
						<text class="item-info-title itemflex">{{$t('finishedInventory.mesInventoryTotal')}}：<text style="color: #333;">{{data.billCodeInfo.MESTotal}}</text></text>
						<text class="item-info-title itemflex">{{$t('finishedInventory.k3InventoryTotal')}}：<text style="color: #333;">{{data.billCodeInfo.K3Total}}</text></text>
					</view>
					
					<view class="custom-card-itemOne addflex">
						<!-- <text class="item-info-title itemflex">MES总托数：<text style="color: #333;">222</text></text> -->
                        <text class="item-info-title itemflex">{{$t('finishedInventory.difference')}}：<text style="color: #333;">{{data.billCodeInfo.difference}}</text></text>
						 <text class="item-info-title itemflex">{{$t('JsInternational.ofStocktaked')}}：<text style="color: #333;">{{data.checkQty}}</text></text>
					</view>
					<view class="custom-card-itemOne addflex">						
					   
					</view>
				</view>
				<!-- 填写内容 -->
				<view class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{$t('distributedEnter.barcodeScan')}}
					</view>
					<view class="custom-card-scan">
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.scanValue" :placeholder="$t('stockManage.pleaseScanCode')" @confirm="confirm" @iconClick="iconClick">
						</uni-easyinput>
					</view>
					<view class="custom-card-itemTwo" >
						<text class="item-info-title">{{$t('distributedEnter.materialCode')}}：</text>
						<comboGrid requestUrl="/mes/basMaterial/getPageSetPDA" v-model="data.materialCode" :requestParam="data.materialParam" inputKey="materialName" :placeholder="$t('distributedEnter.placeholderTextChoose')" gridPlaceholder="输入代码或者名称筛选" :column="data.columnName.column" bindValue="materialCode" @setClick="getMaterialClick"></comboGrid>
						<uni-icons class="iconDelete" type="close" v-if="data.materialCode" size="18" color="#999" @click="handelMaterialClear"></uni-icons>
					</view>
					<view  class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title" style="width:180rpx">{{$t('distributedOut.location')}}：</text>
						<storageBin :ignoreLocationCode="data.ignoreLocationCode" class="gui-text-right"
							requestUrl="/wms/wmsLocation/getIsUsePageSetByFG"
							:requestParam="data.requestParam" :locationUseList="data.locationUseList"
							v-model="data.locationCode"
							@setClick="getLocationClick" style="width:100%"></storageBin>
							<uni-icons class="iconDelete" type="close" v-if="data.locationCode.length" size="18" color="#999" @click="handelClear"></uni-icons>
						<!-- <comboGrid requestUrl="/wms/wmsLocation/getIsUsePageSetByFG" v-model="data.locationCode" :requestParam="data.requestParam" inputKey="locationCode" :placeholder="$t('distributedEnter.placeholderTextChoose')" gridPlaceholder="输入名称筛选" :column="data.columnLocation.column" bindValue="locationName" @setClick="getLocationClick"></comboGrid> -->
					</view>
				</view>
				<!-- 扫描信息 -->
				<view class="gui-flex gui-rows gui-nowrap gui-align-items-center gui-margin-top">
					<view class="gui-title-line"></view>
					<text class="gui-primary-text gui-h6" style="padding-left:50rpx; padding-right:50rpx;">{{$t('finishedInventory.mesFinishedInfo')}}</text>
					<view class="gui-title-line"></view>
				</view>
				<!-- 滑动块 -->
				<scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll">
					<!-- 选两个都选的样式 -->
					<view  class="custom-form-card" v-if="data.materialCode!=''&& data.locationName!=''" v-for="(x,i) in data.checkInfo" :key="i">
						<uni-collapse v-model="data.value">
							<uni-collapse-item titleBorder="none" :show-animation="true">
								<template v-slot:title>
									<view class="custom-card-title" style="color:red">
										<text class="title-line"></text>
										{{$t('finishedInventory.currentMaterial')}}
									</view>
								</template>
								<view class="content">
									<view class="custom-card-itemOne">
											<text class="item-info-title">{{$t('distributedEnter.barcode')}}：</text>{{x.barcode}}
									</view>
									<view class="custom-card-itemOne">
											<text class="item-info-title">{{$t('distributedEnter.materialCode')}}：</text>{{x.materialCode}}
									</view>
									<view class="custom-card-itemOne">
										<text class="item-info-title">{{$t('distributedEnter.materialName')}}：</text>{{x.materialName}}
									</view>
									<view class="custom-card-itemOne">
										<text class="item-info-title">{{$t('distributedOut.location')}}：</text>{{x.locationCode}}
									</view>
									<view class="custom-card-itemOne">
										<text class="item-info-title">{{$t('distributedEnter.qty')}}：</text>{{x.stockQty}}
									</view>
								</view>
							</uni-collapse-item>
						</uni-collapse>
					</view>
					<!-- 选择库位的card的样式-->
					<view  class="custom-form-card" v-if="data.locationCode!=''&& data.materialCode==''" v-for="(x,i) in data.locationMaterials" :key="i">
						<uni-collapse v-model="data.value">
							<uni-collapse-item titleBorder="none" :show-animation="true" >
								<template v-slot:title>
									<view class="custom-card-title">
										<text class="title-line"></text>
										<view class="custom-card-itemOne">
										<text class="item-info-title">{{$t('distributedOut.location')}}：</text>{{x.locationCode}}
									</view>
									</view>
								</template>
								<view class="content">
									<view class="custom-card-itemOne">
											<text class="item-info-title">{{$t('distributedEnter.barcode')}}：</text>{{x.barcode}}
									</view>
									<view class="custom-card-itemOne">
											<text class="item-info-title">{{$t('distributedEnter.materialCode')}}：</text>{{x.materialCode}}
									</view>
									<view class="custom-card-itemOne">
										<text class="item-info-title">{{$t('distributedEnter.materialName')}}：</text>{{x.materialName}}
									</view>
									<view class="custom-card-itemOne">
										<text class="item-info-title">{{$t('distributedEnter.materialSpec')}}：</text>{{x.materialSpec}}
									</view>
									<view class="custom-card-itemOne">
										<text class="item-info-title">{{$t('distributedEnter.qty')}}：</text>{{x.stockQty}}
									</view>
								</view>
							</uni-collapse-item>
						</uni-collapse>
					</view>
					<!-- 选择物料代码的card的样式-->
					<view  class="custom-form-card" v-if="data.materialCode!=''&& data.locationCode==''" v-for="(x,i) in data.materialCodeCard " :key="i">
						<uni-collapse v-model="data.value">
							<uni-collapse-item titleBorder="none" :show-animation="true">
								<template v-slot:title>
									<view class="custom-card-title">
										<text class="title-line"></text>
										<view class="custom-card-itemOne">
										<text class="item-info-title">{{$t('distributedEnter.materialCode')}}：</text>{{x.materialCode}}
									</view>
									</view>
								</template>
								<view class="content">
									<view class="custom-card-itemOne">
											<text class="item-info-title">{{$t('distributedEnter.barcode')}}：</text>{{x.barcode}}
									</view>
									<view class="custom-card-itemOne">
										<text class="item-info-title">{{$t('distributedEnter.materialName')}}：</text>{{x.materialName}}
									</view>
									<view class="custom-card-itemOne">
										<text class="item-info-title">{{$t('distributedEnter.materialSpec')}}：</text>{{x.materialSpec}}
									</view>
									<view class="custom-card-itemOne">
										<text class="item-info-title">{{$t('distributedOut.location')}}：</text>{{x.locationCode}}
									</view>
									<view class="custom-card-itemOne">
										<text class="item-info-title">{{$t('distributedEnter.qty')}}：</text>{{x.stockQty}}
									</view>
								</view>
							</uni-collapse-item>
						</uni-collapse>
					</view>
					
					<!-- 选两个都不选的样式 -->
					<view  class="custom-form-card"  v-if="data.showCard"  v-for="(x,i) in data.listInfo" :key="i">
						<uni-collapse v-model="data.value">
							<uni-collapse-item titleBorder="none" :show-animation="true">
								<template v-slot:title>
									<view class="custom-card-title">
										<text class="title-line"></text>
										{{$t('finishedInventory.barcodeInformation')}}
									</view>
								</template>
								<view class="content">
									<view class="custom-card-itemOne">
											<text class="item-info-title">{{$t('distributedEnter.barcode')}}：</text>{{x.barcode}}
									</view>
									<view class="custom-card-itemOne">
											<text class="item-info-title">{{$t('distributedEnter.materialCode')}}：</text>{{x.materialCode}}
									</view>
									<view class="custom-card-itemOne">
										<text class="item-info-title">{{$t('distributedEnter.materialName')}}：</text>{{x.materialName}}
									</view>
									<view class="custom-card-itemOne">
										<text class="item-info-title">{{$t('distributedOut.location')}}：</text>{{x.locationCode}}
									</view>
									<view class="custom-card-itemOne">
										<text class="item-info-title">{{$t('distributedEnter.qty')}}：</text>{{x.stockQty}}
									</view>
								</view>
							</uni-collapse-item>
						</uni-collapse>
					</view>
				</scroll-view>

				<view class="page-bottom-boxtwo">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="handelCheck">
						{{$t('calendar.submit')}}
					</view>
				</view>
			</view>
		</template>
	</gui-page>
</template>

<script setup>
import { navigate, navigateBack } from '@/utils/routerSkip.js';
import {ref,reactive,toRaw,watch,computed,onMounted} from 'vue';
import storageBin from '@/components/storageBin.vue';
import comboGrid from "@/components/comboGrid";
import { onShow } from '@dcloudio/uni-app';

import {TEST_URL,PROD_URL,IMG_BASE_URL} from '@/constant/config.js'
import {TOKEN} from '@/constant/index.js';
import { basPdaOperationLogFn } from '@/utils/index.js';
import { OPERATION_COMMIT, OPERATION_SCAN } from '@/constant/index.js'
import { getDataDictionaryFn, base64toFile} from '@/utils/index.js'
//API引入
import {selectK3andMESTotal,selectWmsCheckStocked,checkFGStockSubmit} from '@/api/api.js'
//扫描条码的引入
import pdaScan from '@/hooks/pdaScan.js'
import { useStore } from "vuex";
import { forEach } from '../../uni_modules/u-ajax/js_sdk/lib/utils';

//国际化引入
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

const { scan } = pdaScan()
let store = useStore();
// 接受来自父组件的传参 页面传值
const props = defineProps({
	id: String,
	billCode:String,
});

//注册组件
components:{storageBin,comboGrid}

let data = reactive({
	billCodeInfo:[],// 库存信息
	id:props.id,// 上级界面传过来的id
	billCode:props.billCode,//上级界面传过来的billCode

	scanValue:'',//扫描信息
	materialCode:'',//物料编码
	locationCode:'',//库位
	ignoreLocationCode: [],
	checkInfo:[],//物料代码+库位展示
	locationMaterials:[],//库位代码查询物料card绑定的数据
	materialCodeCard:[],//物料代码查询card绑定的数据
	listInfo:[],//进入页面展示的信息

	formData:'',// 签名信息

	value:['0'],//card的展开
	showCard:false,
    barcodeList:[],
	checkQty:0,
	//物料代码的传参
	materialParam: {
		text:'成品',
		materialCode:"",
 		materialName: "",//物料代码,传给接口用的变量
    },
   // 库位的传参
   requestParam:{
		locationCode:""
   },
   //物料代码的下拉选择器
	columnName:{
		column: [{
   			label: t('distributedEnter.materialCode'),
      		name: "materialCode",
   	 	},{
    		label: t('distributedEnter.materialName'),
      		name: "materialName",
      }]
    },
	// 库位的下拉选择器
	columnLocation:{
		column: [{
			label: t('JsInternational.volumnStockName'),
			name: "locationCode",
		},{
			label: t('JsInternational.volumnStockOf'),
			name: "maxCapacity",
		}]
   },
})

// 页面显示就加载
onShow(()=>{
	k3andMESTotal()
	selectMaterial(true)
})

onMounted(()=>{
	store.commit("clearfinishedProductPanDian")
})

// 存储扫描数据到vuex
data.barcodeList = computed(() => {
	return store.state.finishedProductPanDian
})

data.checkQty= computed(() => {
	let sum = 0;
	    store.state.finishedProductPanDian.map(function (item) {
	        sum += item.stockQty;
	    });
		return sum;
})//已扫描数量

// 获取库存数，通过盘点单号获取
const k3andMESTotal=()=>{
	selectK3andMESTotal({
		billCode:data.billCode
	}).then(res=>{
		if (res.status == 200) {
			data.billCodeInfo=res.data;
		}
	})
}

onMounted(()=>{
	console.log('开始监听PDA扫码')
	uni.$on('scancodedate', (data) => {
		console.log('获取到的code：' + data.code)
		getCode(data.code, 'pda')
	})
})

// 用户调起相机扫码
const iconClick = async (type) => {
	console.log(type)
	if (type === 'suffix') {
		let code = await scan()
		getCode(code, 'scan')
	}
}
// 用户点击键盘上搜索
const confirm = () => {
	getCode(data.scanValue, 'keydown')
}

// 获取code，查询barcode信息
const getCode = (code, type) => {
	data.scanValue = code
	let parmes = { //根据barcode查询物料详情
		barcode: data.scanValue,
		masterId:data.id,
		locationCode:'',
		materialCode:''
	}
	selectWmsCheckStocked(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '成品盘点'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode:res.status,//返回状态
				errorMessage:res.message,//错误信息
				isPass:res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType:OPERATION_SCAN
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.status == 200) {
			data.checkInfo = res.data.rows;
			if(data.checkInfo.length){
				data.materialCode=data.checkInfo[0].materialCode;//扫描条码之后将物料号赋值给物料代码
				selectMaterial()
				if(!data.barcodeList.filter(e=>e.barcode==data.checkInfo[0].barcode).length)
				{
					store.commit('addfinishedProductPanDian',data.checkInfo[0])
				}
				
			}
			else{
				uni.showToast({
					title: t('Common.NoData'),
					icon:'none',
					duration:2000
				})

			}

		} else {
			uni.showToast({ title: res.message, icon: "none" });
		}
	})
}

// 物料代码的选择
const getMaterialClick=(x)=>{
	data.materialId=x.id
	data.materialCode=x.materialCode;
	selectMaterial(false)

}

//库位选择之后赋值给变量
const getLocationClick=(x) => {
	data.locationId=x.id
	data.locationName = x.locationName;
	data.locationCode = x.locationCode;
	selectMaterial(false)

}

//物料代码查询
const selectMaterial=(x)=>{
	selectWmsCheckStocked({ //根据物料代码查询物料详情
		barcode:'',
		masterId:data.id,
		locationCode:data.locationCode,
		materialCode:data.materialCode
	}).then(res => {
		if (res.status == 200) {
			// 物料展示
			if(data.materialCode!=""&&data.locationCode==""){
				data.materialCodeCard = res.data.rows;
				data.showCard=x;
			}
			//库位展示
			if(data.materialCode==""&&data.locationCode!=""){
				data.locationMaterials = res.data.rows;
				data.showCard=x;
			}
			//物料代码+库位
			if(data.materialCode!=""&&data.locationCode!=""){
				data.checkInfo = res.data.rows;
				data.showCard=x;
			}
			//物料代码+库位(进入页面没有条件展示)
			if(data.materialCode==""&&data.locationCode==""&&data.scanValue==""){
				data.listInfo = res.data.rows;
				data.showCard=x;
			}
		}
	})
}



// 签名信息
data.formData = computed(() => {
	return store.state.fromDataInventory
})

// 提交接口
const handelCheck = async () => {
	//判断用户是否有提交权限
	let bool = await store.dispatch('checkUser')
	if(!bool){
		uni.showToast({
		title: t('JsInternational.sorryAuthority'),
			icon: 'none'
		})
		return
	}
	//循环盘点单中的所有物料单号
	data.listInfo.forEach(x=>{
		console.log(x)
	})
	//打开签名页面
	if(!data.formData.length){
		navigate({
			url:`/pages/finishedInventory/finishedInventorySignature`
		})
		return
	}
	uploadFile()
}
// 上传图片获取开始上传
const uploadFile = () => {
	let isDev = process.env.NODE_ENV === 'development';
	let baseUrl = isDev ? TEST_URL : PROD_URL
	let token = uni.getStorageSync(TOKEN);
	// let str = base64toFile(data.formData,'file')
	let formData = {
		bizId:data.id,
		// file:str,
		bizType:'wms_checkstock_h'
	}

	uni.showLoading({
		title: t('JsInternational.uploading')
	});
	uni.uploadFile({
		url: baseUrl + '/system/oss/oss-simple', //上传接口
		name: 'file',
		header: {
			// "content-type": "multipart/form-data",
			'token': token
		},
		filePath:data.formData,
		formData:formData,
		success: (uploadFileRes) => {
			uni.hideLoading();
			const back = JSON.parse(uploadFileRes.data);
			if (back.statusCode == 200) {
				// let imgPath = IMG_BASE_URL + back.filePath;
				let imgPath = back.data;
				checkRequest(imgPath)
			} else {
				uni.showToast({title:back.message, icon:"none"});
			}
		},
		fail: () => {
			uni.hideLoading();
			uni.showToast(t('JsInternational.pictureUploading'))
		},
		complete: function() {
			uni.hideLoading();
		}
	});
}
// 生成审核单
const checkRequest = (imgPath)=> {
	let parmes = { //盘点审核接口
		id: data.id, // 收料单id
		auditSign:imgPath,
	}
    checkFGStockSubmit(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '成品盘点'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode:res.status,//返回状态
				errorMessage:res.message,//错误信息
				isPass:res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType:OPERATION_COMMIT
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		console.log(res)
		if (res.status == 200) {
			uni.showToast({
				title: t('smashRemoval.submitSuccessfully'),
				icon: 'none',
				complete: () => {
					//清除 缓存总store签名信息
		            store.commit('delFormDataInventory')
					uni.navigateBack({
					    delta: 1
					});
				}
			})
		} else {
			uni.showToast({ title: res.message, icon: "none" });
		}
	})
}

// 页面跳转到查看记录
const clickRight = () => {
	navigate({
		url:`/pages/finishedInventory/finishedInventoryRecord?id=${data.id}`
	})
}

const handelClear=()=>{
	data.locationCode=""
	data.locationName=""
	data.locationId=null
	if(!data.materialCode)
	{selectMaterial(true)}
	else{selectMaterial(false)}
}

const handelMaterialClear=()=>{
	data.materialId=null
	data.materialCode="";
	if(!data.locationCode){selectMaterial(true)}
	else{selectMaterial(false)}
}
</script>

<style lang="scss" scoped>
// .card-my{
// 	display: flex;
// 	flex-direction: column;
// }
.addflex{
    display: flex;
    align-items: center;
    .itemflex{
        flex: 1;
    }
}
.distributed {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 200rpx);
	// height: 100vh;
}
.scroll {
	margin-top: 15rpx;
	flex: 1;
	height: 2rpx;
}
.page-bottom-box{
	position: fixed;
}
.addborder{
    border: 1rpx solid #DCDFE6;
    box-sizing: border-box;
    padding: 15rpx;
	margin-bottom: 15rpx;
	border-radius: 8rpx;
}
.input-dialog-itembox{
	padding: 15rpx;
	box-sizing: border-box;
	border: 1rpx solid #DCDFE6;
	margin-bottom: 15rpx;
	border-radius: 8rpx;
}
.input-dialog-item{
	font-size: 24rpx;
}
.input, .textarea{
	font-size: 24rpx;
}

.iconDelete{
	margin-top: 20rpx;
	height: 100%;
	width: 40rpx;
}
</style>
